package dyyx.util;

import java.time.LocalDateTime;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyEchoClient {
	
	private final String host;
	private final int port;
    private final Bootstrap bootstrap ;
    private final Channel channel;
	private final NioEventLoopGroup eventLoopGroup;

    
    // private static final String UTF8 = "UTF-8";

	public NettyEchoClient(String host,int port)throws Exception{
		NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
	
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.group(eventLoopGroup)
		.channel(NioSocketChannel.class)
		.remoteAddress(host, port)
		.handler(new ChannelInitializer<Channel>() {

				@Override
				protected void initChannel(Channel ch) throws Exception {
					ch.pipeline().addLast("framer",
							new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
					ch.pipeline().addLast("decoder", new StringDecoder());
					ch.pipeline().addLast("encoder", new StringEncoder());
					ch.pipeline().addLast(new EchoClientHandler());
				}
			});
		Channel ch = bootstrap.connect().sync().channel();
		this.host = host;
		this.port = port;
		this.bootstrap = bootstrap;
		this.channel = ch;
		this.eventLoopGroup = eventLoopGroup;

	}
	
	public ChannelFuture doWriteLine(String str)throws Exception{
		return channel.writeAndFlush(str+"\n");
	}
	
	public void close()throws Exception{
		if(eventLoopGroup==null){
			return;
		}
		eventLoopGroup.shutdownGracefully();
	}
	
	
	private static class EchoClientHandler extends SimpleChannelInboundHandler<Object> {

		@Override
		public void channelActive(ChannelHandlerContext ctx) {

		}

		@Override
		public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
			// 加上 编码解码器后  msg 为 string 类型
			// received:PooledUnsafeDirectByteBuf(ridx: 0, widx: 43, cap: 1024)
			System.out.println("received:" + msg+",at "+LocalDateTime.now());
		
		}

		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

			System.out.println("ERROR:" + cause);
			ctx.close();
		}
	}

	
}
